// Base64 编解码工具
class Base64Encoder {
    /**
     * 编码为 Base64
     * @param {string} input - 要编码的字符串
     * @param {Object} options - 编码选项
     * @returns {Object} - 处理结果
     */
    static encode(input, options = {}) {
        try {
            if (!input) {
                return { success: false, error: '请输入要编码的内容' };
            }

            const { 
                charset = 'utf-8',
                urlSafe = false,
                removePadding = false
            } = options;

            let encoded;
            
            if (charset === 'utf-8') {
                // UTF-8 编码
                encoded = btoa(unescape(encodeURIComponent(input)));
            } else {
                // ASCII 编码
                encoded = btoa(input);
            }

            // URL安全编码
            if (urlSafe) {
                encoded = encoded.replace(/\+/g, '-').replace(/\//g, '_');
            }

            // 移除填充
            if (removePadding) {
                encoded = encoded.replace(/=/g, '');
            }

            return { 
                success: true, 
                data: encoded,
                originalLength: input.length,
                encodedLength: encoded.length,
                ratio: ((encoded.length / input.length) * 100).toFixed(1)
            };
        } catch (error) {
            return { success: false, error: '编码失败: ' + error.message };
        }
    }

    /**
     * 解码 Base64
     * @param {string} input - 要解码的 Base64 字符串
     * @param {Object} options - 解码选项
     * @returns {Object} - 处理结果
     */
    static decode(input, options = {}) {
        try {
            if (!input) {
                return { success: false, error: '请输入要解码的Base64内容' };
            }

            const { 
                charset = 'utf-8',
                urlSafe = false
            } = options;

            let cleanInput = input.trim();

            // 验证 Base64 格式
            const validationResult = this.validate(cleanInput, { urlSafe });
            if (!validationResult.success) {
                return validationResult;
            }

            // URL安全解码
            if (urlSafe) {
                cleanInput = cleanInput.replace(/-/g, '+').replace(/_/g, '/');
            }

            // 补齐填充
            while (cleanInput.length % 4) {
                cleanInput += '=';
            }

            let decoded;
            
            if (charset === 'utf-8') {
                // UTF-8 解码
                decoded = decodeURIComponent(escape(atob(cleanInput)));
            } else {
                // ASCII 解码
                decoded = atob(cleanInput);
            }

            return { 
                success: true, 
                data: decoded,
                originalLength: input.length,
                decodedLength: decoded.length,
                ratio: ((input.length / decoded.length) * 100).toFixed(1)
            };
        } catch (error) {
            return { success: false, error: '解码失败: 输入的Base64格式不正确' };
        }
    }

    /**
     * 验证 Base64 格式
     * @param {string} input - 要验证的字符串
     * @param {Object} options - 验证选项
     * @returns {Object} - 验证结果
     */
    static validate(input, options = {}) {
        try {
            if (!input) {
                return { success: false, error: '输入内容为空' };
            }

            const { urlSafe = false } = options;
            
            // 移除空白字符
            const cleanInput = input.replace(/\s/g, '');
            
            let pattern;
            if (urlSafe) {
                // URL安全Base64字符集
                pattern = /^[A-Za-z0-9\-_]*={0,2}$/;
            } else {
                // 标准Base64字符集
                pattern = /^[A-Za-z0-9+/]*={0,2}$/;
            }

            if (!pattern.test(cleanInput)) {
                return { 
                    success: false, 
                    error: `包含非法字符，${urlSafe ? 'URL安全' : '标准'}Base64只能包含字母、数字${urlSafe ? '、横线和下划线' : '、加号和斜杠'}` 
                };
            }

            // 检查长度
            if (cleanInput.length % 4 !== 0 && !urlSafe) {
                return { success: false, error: '长度不正确，Base64长度必须是4的倍数' };
            }

            // 检查填充位置
            const paddingMatch = cleanInput.match(/=+$/);
            if (paddingMatch && paddingMatch[0].length > 2) {
                return { success: false, error: '填充字符过多，最多只能有2个等号' };
            }

            return { 
                success: true, 
                data: {
                    length: cleanInput.length,
                    hasUrlSafeChars: /-|_/.test(cleanInput),
                    hasPadding: cleanInput.includes('='),
                    paddingLength: paddingMatch ? paddingMatch[0].length : 0
                }
            };
        } catch (error) {
            return { success: false, error: '验证失败: ' + error.message };
        }
    }

    /**
     * 编码文件
     * @param {File} file - 文件对象
     * @returns {Promise<Object>} - 处理结果
     */
    static async encodeFile(file) {
        try {
            if (!file) {
                return { success: false, error: '请选择文件' };
            }

            // 检查文件大小 (限制为10MB)
            const maxSize = 10 * 1024 * 1024;
            if (file.size > maxSize) {
                return { success: false, error: '文件太大，请选择小于10MB的文件' };
            }

            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const result = e.target.result;
                        const base64 = result.split(',')[1]; // 移除data:xxx;base64,前缀
                        
                        resolve({
                            success: true,
                            data: base64,
                            fileInfo: {
                                name: file.name,
                                size: file.size,
                                type: file.type,
                                lastModified: new Date(file.lastModified).toLocaleString()
                            }
                        });
                    } catch (error) {
                        resolve({ success: false, error: '文件编码失败: ' + error.message });
                    }
                };
                reader.onerror = function() {
                    resolve({ success: false, error: '文件读取失败' });
                };
                reader.readAsDataURL(file);
            });
        } catch (error) {
            return { success: false, error: '文件处理失败: ' + error.message };
        }
    }

    /**
     * 解码为文件
     * @param {string} base64Data - Base64数据
     * @param {string} fileName - 文件名
     * @param {string} mimeType - MIME类型
     * @returns {Object} - 处理结果
     */
    static decodeToFile(base64Data, fileName = 'decoded_file', mimeType = 'application/octet-stream') {
        try {
            if (!base64Data) {
                return { success: false, error: '请输入Base64数据' };
            }

            // 验证Base64
            const validation = this.validate(base64Data);
            if (!validation.success) {
                return validation;
            }

            // 转换为Blob
            const byteCharacters = atob(base64Data);
            const byteNumbers = new Array(byteCharacters.length);
            
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            
            const byteArray = new Uint8Array(byteNumbers);
            const blob = new Blob([byteArray], { type: mimeType });

            return {
                success: true,
                data: {
                    blob: blob,
                    fileName: fileName,
                    size: blob.size,
                    type: mimeType,
                    url: URL.createObjectURL(blob)
                }
            };
        } catch (error) {
            return { success: false, error: '解码为文件失败: ' + error.message };
        }
    }

    /**
     * 获取常用MIME类型
     */
    static getMimeTypes() {
        return {
            'txt': 'text/plain',
            'html': 'text/html',
            'css': 'text/css',
            'js': 'application/javascript',
            'json': 'application/json',
            'xml': 'application/xml',
            'pdf': 'application/pdf',
            'zip': 'application/zip',
            'jpg': 'image/jpeg',
            'jpeg': 'image/jpeg',
            'png': 'image/png',
            'gif': 'image/gif',
            'svg': 'image/svg+xml',
            'mp3': 'audio/mpeg',
            'mp4': 'video/mp4',
            'doc': 'application/msword',
            'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xls': 'application/vnd.ms-excel',
            'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        };
    }
}